package com.example.fireassistant_server.controller;
import com.example.fireassistant_server.dto.file.FileUploadRequest;
import com.example.fireassistant_server.entity.TmpSecret;
import com.example.fireassistant_server.mapper.FileMapper;
import com.example.fireassistant_server.service.FileService;
import com.example.fireassistant_server.vo.FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

//携带token的注册用户即可访问
@PreAuthorize("hasRole('ROLE_USER')")
@RestController
@RequestMapping("/files")
public class FileController {

    private FileService fileService;

    private FileMapper fileMapper;

    // 获取临时令牌
    @GetMapping("/tmp")
    public TmpSecret getTmpSecret() throws IOException {
        return fileService.getTmpSecret();
    }

    @PostMapping("/upload_init")
    public FileVo initUpload(@Validated @RequestBody FileUploadRequest fileUploadRequest) throws IOException {
        return fileMapper.toVo(fileService.initUpload(fileUploadRequest));
    }


    @PostMapping("/{id}/upload_finish")
    public FileVo finishUpload(@PathVariable String id) {
        return fileMapper.toVo(fileService.finishUpload(id));
    }




    //删除相关文件 谁创建、谁删除或者区域管理员可以删除，在前端实现
    //TODO 对象存储中的文件删除
    @DeleteMapping("/{type}/{id}")
    void delete(@PathVariable("type") String type, @PathVariable("id") String id) {
        fileService.delete(type, id);
    }

    @Autowired
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }



    @Autowired
    public void setFileMapper(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }
}
